package com.zhipu.balance.ui.vm.home.calculate.soybean

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zhipu.balance.common.Constants
import com.zhipu.balance.listener.ChooseClickCallback
import com.zhipu.balance.listener.SerialPortListener
import com.zhipu.balance.mobile.dao.NumberDao
import com.zhipu.balance.mobile.dao.RecordCornDao
import com.zhipu.balance.mobile.dao.RecordSoybeanDao
import com.zhipu.balance.mobile.event.RecordDaMi
import com.zhipu.balance.mobile.event.RecordRapeseed
import com.zhipu.balance.mobile.event.RecordRice
import com.zhipu.balance.mobile.event.RecordSoybean
import com.zhipu.balance.pop.ConfirmPopup
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.calculate.dami.*
import com.zhipu.balance.ui.home.calculate.dami.adapter.DaMiAdapter
import com.zhipu.balance.ui.home.calculate.rapeseed.RapeseedActivity
import com.zhipu.balance.ui.home.calculate.rice.*
import com.zhipu.balance.ui.home.calculate.rice.adapter.RiceAdapter
import com.zhipu.balance.ui.home.calculate.soybean.*
import com.zhipu.balance.ui.home.calculate.soybean.adapter.SoybeanAdapter
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.OpenSerialPort
import com.zhipu.balance.utils.data.DisposeUtils
import com.zhipu.balance.utils.print.dami.DaMiPrintUtils
import com.zhipu.balance.utils.print.rice.RicePrintUtils
import com.zhipu.balance.utils.print.soybean.SoybeanPrintUtils
import com.zhipu.balance.utils.print.wheat.WheatPrintUtils
import com.zhipu.balance.utils.upload.dami.DaMiUploadUtils
import com.zhipu.balance.utils.upload.soybean.SoybeanUploadUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 功能计算-大豆
 */
class SoybeanViewModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService), SerialPortListener,ChooseClickCallback {
    /**
     * 称重重量
     */
    var weighing = ObservableField("0.00")

    /**
     * 去皮
     */
    var peel = ObservableField(false)

    /**
     * 位置
     */
    var mPosition = MutableLiveData(0)

    /**
     * 编号
     */
    var mNumber = ObservableField("")

    /**
     * 日期
     */
    var mInspectionDate = ObservableField("")

    /**
     * 记录大豆
     */
    var mRecordSoybean = RecordSoybean()



    /**
     * 适配器
     */
    var mSoybeanAdapter : SoybeanAdapter? = null



    /**
     *  Fragment集合
     */
    var mFragments = MutableLiveData<List<Fragment>>()

    /**
     * 大豆杂质
     */
    var mSoybeanImpurityFragment = SoybeanImpurityFragment(mRecordSoybean)

    /**
     * 大豆损伤粒
     */
    var mSoybeanDamageFragment = SoybeanDamageFragment(mRecordSoybean)

    /**
     * 大豆热损伤粒
     */
    var mSoybeanHotDamageFragment = SoybeanHotDamageFragment(mRecordSoybean)

    /**
     * 大豆完整粒
     */
    var mSoybeanCompleteFragment = SoybeanCompleteFragment(mRecordSoybean)


    init {
        OpenSerialPort.onSerialPortListener(this)
        /**
         * 每隔milliseconds毫秒后执行next操作
         */
        Observable.interval(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(object :
            Observer<Long> {

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: Long) {
                /**
                 * 重量輸出命令
                 */
                OpenSerialPort.output()
            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }

        })
        /**
         * Fragment适配器
         */
        var mFragmentList = mutableListOf<Fragment>()
        //大豆杂质
        mFragmentList.add(mSoybeanImpurityFragment)
        //大豆损伤粒
        mFragmentList.add(mSoybeanDamageFragment)
        //大豆热损伤粒
        mFragmentList.add(mSoybeanHotDamageFragment)
        //大豆完整粒
        mFragmentList.add(mSoybeanCompleteFragment)

        /**
         * Fragment集合
         */
        mFragments.postValue(mFragmentList)
        /**
         * 适配器
         */
        mSoybeanAdapter = SoybeanAdapter(this);

    }

    /**
     * 重量回调
     */
    override fun itemClicked(event: ByteArray?) {
        /**
         * 数值
         */
        val numericalValue = ConvertUtils.bytes2HexString(event)
        if (event!!.size >= 10) {
            if (numericalValue == Constants.FARMAR_500) {
                weighing.set("砝码500")
            } else if (numericalValue == Constants.FARMAR_1000) {
                weighing.set("砝码1000")
            } else if (numericalValue == Constants.FARMAR_2000) {
                weighing.set("砝码2000")
            }else if (numericalValue == Constants.FARMAR_3000) {
                weighing.set("砝码3000")
            } else if (numericalValue == Constants.CALIBRATION_500) {
                weighing.set("完成定标")
            } else if (numericalValue == Constants.OVERLOAD) {
                weighing.set("超重")
            } else if (numericalValue == Constants.SEND_GO_START) {
                InitializeUtils.getDefaultMaker()?.show("去皮成功")
                peel.set(false)
            }  else if (numericalValue == Constants.SHIELD) {
                weighing.set("校准中")
            } else {
                if(peel.get() == true){
                    /**
                     * 置零命令
                     */
                    OpenSerialPort.ZeroOrder()
                }
                var weight = DisposeUtils.balanceCorrection(event)
                //大豆杂质
                mSoybeanImpurityFragment.setWeighing(weight)
                //大豆损伤粒
                mSoybeanDamageFragment.setWeighing(weight)
                //大豆热损伤粒
                mSoybeanHotDamageFragment.setWeighing(weight)
                //大豆完整粒
                mSoybeanCompleteFragment.setWeighing(weight)
                weighing.set(weight)
            }
        }
    }


    /**
     * Fragment回调
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun onChooseClickCallback(mInt: Int) {
        mSoybeanAdapter?.notifyDataSetChanged()
        mPosition.postValue(mInt)
        when(mInt){
            0 ->{
                //大豆杂质
                mSoybeanImpurityFragment.updateRecordRice(mRecordSoybean)
            }
            1 ->{
                //大豆损伤粒
                mSoybeanDamageFragment.updateRecordRice(mRecordSoybean)
                mSoybeanDamageFragment.refreshData()
            }
            2 ->{
                //大豆热损伤粒
                mSoybeanHotDamageFragment.updateRecordRice(mRecordSoybean)
                mSoybeanHotDamageFragment.refreshData()
            }
            3 ->{
                //大豆完整粒
                mSoybeanCompleteFragment.updateRecordRice(mRecordSoybean)
                mSoybeanCompleteFragment.refreshData()
            }
        }
    }


    /**
     * 更新数据
     */
    fun UpdatePage(productCategoryText : String){
        var mRecordSoybean = RecordSoybeanDao.getInstance().QueryByNumber(productCategoryText)
        if(mRecordSoybean.recordSoybeanId > 0){
            this.mRecordSoybean = mRecordSoybean
            //日期
            mInspectionDate.set(TimeUtils.millis2String(mRecordSoybean.inspectionDate))
            //大豆杂质
            mSoybeanImpurityFragment.updateRecordRice(mRecordSoybean)
            //大豆损伤粒
            mSoybeanDamageFragment.updateRecordRice(mRecordSoybean)
            //大豆热损伤粒
            mSoybeanHotDamageFragment.updateRecordRice(mRecordSoybean)
            //大豆完整粒
            mSoybeanCompleteFragment.updateRecordRice(mRecordSoybean)
        }else{
            //唯一识别码
            mRecordSoybean.uniqueId = productCategoryText
            //日期
            mInspectionDate.set(TimeUtils.millis2String(TimeUtils.getNowMills()))
        }
        //编号
        mNumber.set(productCategoryText)

    }

    /**
     * 释放更新页面
     */
    fun releaseRecordRice(){
        mRecordSoybean = RecordSoybean()
        //大豆杂质
        mSoybeanImpurityFragment.releaseRecordRice()
        //大豆损伤粒
        mSoybeanDamageFragment.releaseRecordRice()
        //大豆热损伤粒
        mSoybeanHotDamageFragment.releaseRecordRice()
        //大豆完整粒
        mSoybeanCompleteFragment.releaseRecordRice()
        //编号
        mNumber.set("")
        //日期
        mInspectionDate.set("")
    }



    /**
     * 保存
     */
    fun save(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    //唯一识别码
                    mRecordSoybean.uniqueId = mNumber.get()
                    //判断
                    if(mRecordSoybean.recordSoybeanId > 0){
                        //设备码
                        mRecordSoybean.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        mRecordSoybean.update()
                    }else{
                        //设备码
                        mRecordSoybean.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        if(mRecordSoybean.save()){
                            /**
                             * 上传
                             */
                            val NetworkSettings = SPUtils.getInstance().getString("NetworkSettings")
                            if(TextUtils.isEmpty(NetworkSettings)){
                                //外网上传大豆天平数据
                                SoybeanUploadUtils.uploadSoybeanBalanceInfo(mRecordSoybean,null)
                            }else{
                                //内网上传大豆天平数据
                                SoybeanUploadUtils.IntranetSoybeanBalanceInfo(mRecordSoybean,null)
                            }
                        }
                    }
                    /**
                     * 释放更新页面
                     */
                    releaseRecordRice()
                    /**
                     * 数量加一
                     */
                    SPUtils.getInstance().put("number", SPUtils.getInstance().getInt("number") + 1)
                }
            }
        },"确认要进行上传并保存吗\n确认之后会进行新一轮的计算")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }




    /**
     * 更新页面
     */
    fun updatePage(mRecordSoybean : RecordSoybean){
        this.mRecordSoybean = mRecordSoybean
        //编号
        mNumber.set(mRecordSoybean.uniqueId)
        //日期
        mInspectionDate.set(TimeUtils.millis2String(mRecordSoybean.inspectionDate))
        //大豆杂质
        mSoybeanImpurityFragment.updateRecordRice(mRecordSoybean)
        //大豆损伤粒
        mSoybeanDamageFragment.updateRecordRice(mRecordSoybean)
        //大豆热损伤粒
        mSoybeanHotDamageFragment.updateRecordRice(mRecordSoybean)
        //大豆完整粒
        mSoybeanCompleteFragment.updateRecordRice(mRecordSoybean)
    }



    /**
     * 打印
     */
    fun print(){
        if(InitializeUtils.isLinkPrinter()){
            var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
                override fun onChooseClickCallback(mInt: Int) {
                    if(mInt == 0){
                        SoybeanPrintUtils.SoybeanPrinting(mRecordSoybean)
                    }
                }
            },"确认需要打印吗?")
            XPopup.Builder(ActivityUtils.getTopActivity())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .autoOpenSoftInput(false)
                .asCustom(mConfirmPopup)
                .show()
        }else{
            InitializeUtils.getDefaultMaker()?.show("正在链接打印机")
            InitializeUtils.LinkPrinterModel(ActivityUtils.getTopActivity())
        }
    }

    /**
     * 去皮
     */
    fun peel(){
        InitializeUtils.getDefaultMaker()?.show("正在去皮请稍后")
        /**
         * 去皮
         */
        peel.set(true)
        /**
         * 置零命令
         */
        OpenSerialPort.ZeroOrder()
    }

    /**
     * 计算
     */
    fun calculation(){
        when(mPosition.value){
            0->{
                //大豆杂质
                mSoybeanImpurityFragment.calculation()
            }
            1->{
                //大豆损伤粒
                mSoybeanDamageFragment.calculation()
            }
            2->{
                //大豆热损伤粒
                mSoybeanHotDamageFragment.calculation()
            }
            3->{
                //大豆完整粒
                mSoybeanCompleteFragment.calculation()
            }

        }
        /**
         *  编号
         */
        if(TextUtils.isEmpty(mNumber.get())){
            var number = NumberDao.getInstance().acquireNumber()
            if(null != number){
                if(SPUtils.getInstance().getLong("NumberedDate") > 0){
                    val DAY = TimeUtils.getTimeSpan(
                        SPUtils.getInstance().getLong("NumberedDate"),
                        TimeUtils.getNowMills(),
                        TimeConstants.DAY
                    )
                    if (DAY == 0L) {
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordSoybean.uniqueId = numberString
                        mNumber.set(numberString)
                    }else{
                        SPUtils.getInstance().put("number", 1)
                        SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordSoybean.uniqueId = numberString
                        mNumber.set(numberString)
                    }
                }
            }
        }
        /**
         * 日期
         */
        var getNowMills = TimeUtils.getNowMills()
        mInspectionDate.set(TimeUtils.millis2String(getNowMills))
        mRecordSoybean.inspectionDate = getNowMills
    }
    /**
     * 主菜单
     */
    fun mainMenu(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    ActivityUtils.finishActivity(SoybeanActivity::class.java)
                }
            }
        },"返回主菜单会导致当前数据丢失")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }
}